import { FC, ReactElement, useEffect, memo, useRef } from 'react'
import { connect, UserModelState, Dispatch, userListType } from 'umi'
import { Modal, Form, Input, Select, TreeSelect, message } from 'antd'
import { findNode } from '@/utils'
import type { FormInstance } from 'antd'
interface IProps {
  visible: boolean
  hide: () => void
  dispatch: Dispatch
  userModel: UserModelState
  record: userListType | undefined
  update: () => void
}
interface FormValues {
  [name: string]: any
}
const { Option } = Select
const { TreeNode } = TreeSelect
const EditUser: FC<IProps> = ({
  visible,
  hide,
  dispatch,
  userModel,
  record,
  update
}): ReactElement => {
  const formRef = useRef<FormInstance>(null)
  const { userInfo, gradeList, unitList, roleList } = userModel

  //   查询系统角色列表
  const getRoleList = () => {
    dispatch({
      type: 'userModel/function_getRoleList'
    })
  }
  //   通过用户编号查询用户信息
  const getUserInfoByCode = () => {
    dispatch({
      type: 'userModel/function_getUserInfoByCode',
      payload: {
        userCode: record!.userCode
      }
    })
  }

  const onFinish = (values: FormValues) => {
    const { grade, unitCode } = values
    dispatch({
      type: 'userModel/function_saveUserInfo',
      payload: {
        userCode: record!.userCode,
        ...values,
        grade: grade.join(','),
        unitCode: unitCode.join(',')
      },
      callback: (response) => {
        if (response.code === 200) {
          message.success('编辑成功')
          handleCancel()
          update()
        }
      }
    })
  }

  const onChange = (newValue: any[]) => {
    formRef.current?.setFieldsValue({
      unitCode: newValue.length ? [newValue.at(-1).value] : undefined
    })
    if (!newValue.length) {
      formRef.current?.validateFields(['unitCode'])
    }
  }

  const gradeChange = (value: string[]) => {
    let temp: string[]
    if (value.length && value.at(-1) === '') {
      temp = ['']
      getUnitInfo('')
    } else if (!value.length) {
      temp = []
    } else if (value.length == gradeList.length) {
      temp = ['']
      getUnitInfo('')
    } else {
      temp = value.filter((item) => item)
      getUnitInfo(temp.join(','))
    }
    formRef.current?.setFieldsValue({
      grade: temp
    })
  }
  const handleOk = () => {
    formRef.current?.submit()
  }
  const handleCancel = () => {
    hide()
    formRef.current?.resetFields()
  }

  const renderTree = (data: any[]) => {
    return data.map((item) => {
      if (item.children?.length) {
        return (
          <TreeNode value={item.code} title={item.name} key={item.code}>
            {renderTree(item.children)}
          </TreeNode>
        )
      } else {
        return (
          <TreeNode
            value={item.code}
            title={item.name}
            key={item.code}
          ></TreeNode>
        )
      }
    })
  }

  // 查询机构
  const getUnitInfo = (grade?: string) => {
    dispatch({
      type: 'userModel/function_getUnitInfo',
      payload: { grade }
    })
  }

  // 查询学段
  const getGradeInfo = () => {
    dispatch({
      type: 'userModel/function_getGradeInfo',
      payload: {}
    })
  }

  useEffect(() => {
    if (visible) {
      getUserInfoByCode()
      getGradeInfo()
      getRoleList()
      getUnitInfo()
    }
  }, [visible])
  useEffect(() => {
    formRef.current?.setFieldsValue({
      ...record,
      ...userInfo,
      grade: userInfo.grade?.split(',') ?? [''],
      unitCode: [userInfo.unitCode]
    })
  }, [userInfo])
  useEffect(() => {
    if (unitList.length && visible) {
      const unitCode = formRef.current?.getFieldsValue(['unitCode'])
        .unitCode?.[0]
      const result = findNode(unitList, (node) => node.code === unitCode)
      if (!result) {
        formRef.current?.setFieldsValue({
          unitCode: undefined
        })
      }
    }
  }, [unitList])
  return (
    <Modal
      title="修改用户信息"
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      width="40%"
      okText="确认"
      cancelText="取消"
      maskClosable={false}
    >
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        autoComplete="off"
        ref={formRef}
        onFinish={onFinish}
      >
        <Form.Item
          label="登录账号"
          name="accountName"
          rules={[{ required: true, message: '请输入登录账号!' }]}
        >
          <Input placeholder="请输入登录账号" />
        </Form.Item>
        <Form.Item
          label="姓名"
          name="userName"
          rules={[{ required: true, message: '请输入姓名!' }]}
        >
          <Input placeholder="请输入姓名" />
        </Form.Item>
        <Form.Item
          label="学段"
          name="grade"
          rules={[{ required: true, message: '请选择所属学段!' }]}
        >
          <Select
            placeholder="请选择所属学段"
            allowClear
            mode="multiple"
            onChange={gradeChange}
          >
            <Option value="">全部</Option>
            {gradeList.map((item) => (
              <Option value={item.dictKey} key={item.dictKey}>
                {item.dictValue}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="手机号"
          name="userPhone"
          rules={[
            { required: true, message: '请输入手机号!' },
            {
              pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
              message: '请输入正确格式的手机号码'
            }
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          label="所属机构"
          name="unitCode"
          rules={[{ required: true, message: '请选择所属机构!' }]}
        >
          <TreeSelect
            placeholder="请选择所属机构"
            treeCheckStrictly
            treeDefaultExpandAll
            treeCheckable
            onChange={onChange}
          >
            {renderTree(unitList)}
          </TreeSelect>
        </Form.Item>
        <Form.Item
          label="所属角色"
          name="roleCode"
          rules={[{ required: true, message: '请选择所属角色!' }]}
        >
          <Select placeholder="请选择所属角色">
            {roleList
              .filter((item) => item.status === '1')
              .map((item) => (
                <Option value={item.code} key={item.code}>
                  {item.name}
                </Option>
              ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="启用短信登录"
          name="smsValidate"
          rules={[{ required: true, message: '是否启用短信登录!' }]}
        >
          <Select placeholder="请选择">
            <Option value={'0'}>不启用</Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="状态"
          name="status"
          rules={[{ required: true, message: '请选择状态!' }]}
        >
          <Select placeholder="请选择状态">
            <Option value={'0'}>禁用</Option>
            <Option value={'1'}>启用</Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}

const mapStateToProps = ({ userModel }: { userModel: UserModelState }) => {
  return {
    userModel
  }
}

export default connect(mapStateToProps)(memo(EditUser))
